package com.zelin.web.servlet;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.zelin.pojo.Classes;
import com.zelin.pojo.Student;
import com.zelin.service.ClassesService;
import com.zelin.service.StudentService;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * ------------------------------
 * 功能：
 * 作者：WF
 * 微信：hbxfwf13590332912
 * 创建时间：2021/10/12-16:59
 * ------------------------------
 */
@WebServlet("/classes")
public class ClassesServlet extends HttpServlet {
    private ClassesService classesService;
    @Override
    public void init() throws ServletException {
        WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext());
        classesService = wac.getBean(ClassesService.class);
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. 得到请求参数
        String cmd = req.getParameter("cmd");
        //2. 根据参数调用不同的方法
        if(StrUtil.isNotBlank(cmd)){
            if("list".equalsIgnoreCase(cmd)){
                list(req,resp);
            }
        }
    }
    //1. 查看学生列表
    private void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.1 得到学生列表
        List<Classes> students = classesService.findAll();
        //1.2 将学生列表转换为json送到页面
        resp.getWriter().println(JSON.toJSONString(students));
        resp.getWriter().flush();
    }

}
